<template>
  <div class="job-seeker-container">
    <!-- 头部操作栏 -->
    <div class="action-bar">
      <el-button 
        type="primary" 
        size="large" 
        class="action-button" 
        @click="showAddDialog"
        v-if="resumes.length === 0"
      >
        <i class="el-icon-plus"></i> 新增求职意向
      </el-button>
      <el-button size="large" class="action-button" @click="goToHome">
        <i class="el-icon-back"></i> 返回主页
      </el-button>
    </div>

    <!-- 主要内容区域 -->
    <div class="main-content">
      <!-- 左侧求职意向卡片列表 -->
      <div class="resume-grid">
        <el-card
          v-for="resume in resumes"
          :key="resume.profile_id"
          class="resume-card"
          shadow="hover"
        >
          <template #header>
            <div class="card-header">
              <span class="resume-title">{{ resume.desired_position }}</span>
              <div class="card-actions">
                <el-button type="primary" size="small" class="card-button edit-btn" @click="editResume(resume)">
                  编辑
                </el-button>
                <el-button type="danger" size="small" class="card-button delete-btn" @click="deleteResume(resume.profile_id)">
                  删除
                </el-button>
              </div>
            </div>
          </template>

          <div class="card-content">
            <p><strong>求职状态:</strong> {{ resume.current_status }}</p>
            <p><strong>工作经验:</strong> {{ resume.experience_years || '未填写' }}年</p>
            <p><strong>期望薪资:</strong> {{ resume.expected_salary || '面议' }}</p>
            <p><strong>教育背景:</strong> {{ resume.education_level || '未填写' }}</p>
            <div class="skills-section">
              <p><strong>专业技能:</strong></p>
              <p class="skills-text">{{ resume.skills || '未填写' }}</p>
            </div>
            <p class="update-time">最后更新: {{ formatDate(resume.last_updated) }}</p>
          </div>
        </el-card>
      </div>

      <!-- 右侧申请记录 -->
      <div class="application-panel">
        <el-card class="application-card">
          <template #header>
            <div class="card-header">
              <span class="panel-title">申请记录</span>
            </div>
          </template>
          <el-table :data="applications" size="small" stripe>
            <el-table-column label="职位名称" min-width="150">
              <template #default="{ row }">
                {{ jobTitles[row.job_id] || '加载中...' }}
              </template>
            </el-table-column>
            <el-table-column prop="apply_time" label="申请时间" width="120">
              <template #default="{ row }">{{ formatDate(row.apply_time) }}</template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="120">
              <template #default="{ row }">
                <el-tag :type="getStatusType(row.status)">{{ row.status }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="120">
              <template #default="{ row }">
                <el-button type="text" @click="viewJobDetails(row.job_id)">查看职位</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </div>
    </div>

    <!-- 职位详情对话框 -->
    <el-dialog v-model="jobDialogVisible" title="职位详情" width="50%">
      <div v-if="selectedJob">
        <h3>{{ selectedJob.job_title }}</h3>
        <p><strong>公司名称:</strong> {{ selectedJob.company_name }}</p>
        <p><strong>工作地点:</strong> {{ selectedJob.location }}</p>
        <p><strong>薪资范围:</strong> {{ selectedJob.salary_range || '面议' }}</p>
        <div class="job-description">
          <p><strong>职位描述:</strong></p>
          <p class="description-text">{{ selectedJob.job_description }}</p>
        </div>
        <div class="job-requirements">
          <p><strong>职位要求:</strong></p>
          <p class="description-text">{{ selectedJob.requirements }}</p>
        </div>
      </div>
    </el-dialog>

    <!-- 新增/编辑求职意向弹窗 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="60%"
      class="resume-dialog"
    >
      <el-form :model="currentResume" label-width="120px">
        <el-form-item label="求职岗位" required>
          <el-input v-model="currentResume.desired_position" placeholder="请输入期望的岗位职位" />
        </el-form-item>

        <el-form-item label="求职状态" required>
          <el-select v-model="currentResume.current_status" placeholder="请选择当前求职状态">
            <el-option
              v-for="item in statusOptions"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="工作经验">
          <el-input-number
            v-model="currentResume.experience_years"
            :min="0"
            :max="50"
            placeholder="请输入工作年限"
          />
        </el-form-item>

        <el-form-item label="期望薪资">
          <el-input v-model="currentResume.expected_salary" placeholder="例如：10k-15k" />
        </el-form-item>

        <el-form-item label="教育背景">
          <el-input v-model="currentResume.education_level" placeholder="请输入最高学历或学校专业" />
        </el-form-item>

        <el-form-item label="专业技能">
          <el-input
            v-model="currentResume.skills"
            type="textarea"
            :rows="4"
            placeholder="请输入您的专业技能、证书等，用逗号分隔"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button size="large" class="cancel-btn" @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" size="large" class="save-btn" @click="saveResume" :loading="loading">保存</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useAuthStore } from '../store/auth'

const router = useRouter()
const authStore = useAuthStore()
const loading = ref(false)

// 求职意向数据
const resumes = ref([])

// 当前操作的求职意向
const currentResume = ref({
  profile_id: null,
  desired_position: '',
  current_status: '',
  experience_years: null,
  expected_salary: '',
  education_level: '',
  skills: ''
})

// 弹窗控制
const dialogVisible = ref(false)
const dialogTitle = ref('新增求职意向')
const isEditing = ref(false)

// 状态选项
const statusOptions = [
  '在职-考虑机会',
  '离职-随时到岗',
  '在校学生'
]

// 修改申请记录相关
const applications = ref([])
const jobTitles = reactive({})
const jobDialogVisible = ref(false)
const selectedJob = ref(null)

// 获取求职意向列表
const fetchResumes = async () => {
  try {
    loading.value = true;
    
    const userId = authStore.userId || localStorage.getItem('user_id');
    if (!userId) {
      ElMessage.warning('请先登录');
      router.push('/login');
      return;
    }
    
    const token = authStore.token || localStorage.getItem('token');
    if (!token) {
      ElMessage.warning('认证失败，请重新登录');
      router.push('/login');
      return;
    }
    
    const response = await fetch(`http://127.0.0.1:8000/api/job-seeker-profiles?user_id=${userId}`, {
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${encodeURIComponent(token)}`
      }
    })

    if (!response.ok) {
      const errorText = await response.text();
      throw new Error(`获取求职意向失败: ${errorText}`)
    }

    resumes.value = await response.json()
  } catch (error) {
    ElMessage.error(error.message)
  } finally {
    loading.value = false;
  }
}

// 显示新增弹窗
const showAddDialog = () => {
  // 检查是否已有简历
  if (resumes.value.length > 0) {
    ElMessage.warning('您已经创建了求职意向，每个用户只能创建一份')
    return
  }
  
  currentResume.value = {
    profile_id: null,
    desired_position: '',
    current_status: '',
    experience_years: null,
    expected_salary: '',
    education_level: '',
    skills: ''
  }
  dialogTitle.value = '新增求职意向'
  isEditing.value = false
  dialogVisible.value = true
}

// 编辑求职意向
const editResume = (resume) => {
  currentResume.value = { ...resume }
  dialogTitle.value = '编辑求职意向'
  isEditing.value = true
  dialogVisible.value = true
}

// 保存求职意向
const saveResume = async () => {
  try {
    loading.value = true;
    
    // 验证必填字段
    if (!currentResume.value.desired_position || !currentResume.value.current_status) {
      ElMessage.warning('请填写求职岗位和当前状态')
      loading.value = false;
      return;
    }

    const userId = authStore.userId || localStorage.getItem('user_id');
    if (!userId) {
      ElMessage.warning('用户未登录，请重新登录');
      router.push('/login');
      return;
    }
    
    const token = authStore.token || localStorage.getItem('token');
    if (!token) {
      ElMessage.warning('认证失败，请重新登录');
      router.push('/login');
      return;
    }

    const url = isEditing.value
      ? `http://127.0.0.1:8000/api/job-seeker-profiles/${currentResume.value.profile_id}`
      : 'http://127.0.0.1:8000/api/job-seeker-profiles'

    const method = isEditing.value ? 'PUT' : 'POST'

    // 构建请求体，包含user_id字段
    const requestBody = {
      ...currentResume.value,
      user_id: parseInt(userId)
    };
    
    console.log('发送请求体:', requestBody);

    const response = await fetch(url, {
      method,
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${encodeURIComponent(token)}`
      },
      body: JSON.stringify(requestBody)
    })

    if (!response.ok) {
      const errorText = await response.text();
      throw new Error(`保存失败: ${errorText}`)
    }

    ElMessage.success(isEditing.value ? '更新成功' : '发布成功')
    dialogVisible.value = false
    fetchResumes()
  } catch (error) {
    ElMessage.error(error.message)
  } finally {
    loading.value = false;
  }
}

// 删除求职意向
const deleteResume = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除这份求职意向吗?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    loading.value = true;
    
    const userId = authStore.userId || localStorage.getItem('user_id');
    if (!userId) {
      ElMessage.warning('用户未登录，请重新登录');
      router.push('/login');
      return;
    }
    
    const token = authStore.token || localStorage.getItem('token');
    if (!token) {
      ElMessage.warning('认证失败，请重新登录');
      router.push('/login');
      return;
    }
    
    const response = await fetch(`http://127.0.0.1:8000/api/job-seeker-profiles/${id}?user_id=${userId}`, {
      method: 'DELETE',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${encodeURIComponent(token)}`
      }
    })

    if (!response.ok) {
      const errorText = await response.text();
      throw new Error(`删除失败: ${errorText}`)
    }

    ElMessage.success('删除成功')
    fetchResumes()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(error.message)
    }
  } finally {
    loading.value = false;
  }
}

// 返回主页
const goToHome = () => {
  router.push('/')
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit'
  })
}

// 获取申请记录
const fetchApplications = async () => {
  try {
    loading.value = true
    const token = authStore.token
    const res = await fetch(`http://127.0.0.1:8000/api/applications?applicant_id=${authStore.userId}`, {
      headers: { 'Authorization': `Bearer ${encodeURIComponent(token)}` }
    })
    if (!res.ok) throw new Error(await res.text())
    applications.value = await res.json()
    
    // 获取所有相关职位的标题
    for (const app of applications.value) {
      if (!jobTitles[app.job_id]) {
        await fetchJobTitle(app.job_id)
      }
    }
  } catch (err) {
    ElMessage.error('获取申请记录失败: ' + err.message)
  } finally {
    loading.value = false
  }
}

// 获取职位标题
const fetchJobTitle = async (jobId) => {
  try {
    const token = authStore.token
    const res = await fetch(`http://127.0.0.1:8000/api/job-postings/${jobId}`, {
      headers: { 'Authorization': `Bearer ${encodeURIComponent(token)}` }
    })
    if (!res.ok) throw new Error(await res.text())
    const job = await res.json()
    jobTitles[jobId] = job.job_title
  } catch (err) {
    console.error('获取职位信息失败:', err)
    jobTitles[jobId] = '未知职位'
  }
}

// 获取状态标签类型
const getStatusType = (status) => {
  const types = {
    '已投递': 'info',
    '已查看': 'warning',
    '面试中': 'primary',
    '已录用': 'success',
    '已拒绝': 'danger'
  }
  return types[status] || 'info'
}

// 查看职位详情
const viewJobDetails = async (jobId) => {
  try {
    loading.value = true
    const token = authStore.token
    const res = await fetch(`http://127.0.0.1:8000/api/job-postings/${jobId}`, {
      headers: { 'Authorization': `Bearer ${encodeURIComponent(token)}` }
    })
    if (!res.ok) throw new Error(await res.text())
    selectedJob.value = await res.json()
    jobDialogVisible.value = true
  } catch (err) {
    ElMessage.error('获取职位详情失败: ' + err.message)
  } finally {
    loading.value = false
  }
}

// 组件挂载时获取数据
onMounted(() => {
  fetchResumes()
  fetchApplications() // 直接获取申请记录
})
</script>

<style scoped>
.job-seeker-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.action-bar {
  margin-bottom: 30px;
  display: flex;
  justify-content: space-between;
}

.action-button {
  padding: 12px 24px;
  font-size: 16px;
  font-weight: 500;
  border-radius: 8px;
  transition: all 0.3s ease;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.action-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 16px 0 rgba(0, 0, 0, 0.2);
}

.main-content {
  display: flex;
  gap: 20px;
}

.resume-grid {
  flex: 1;
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(400px, 1fr));
  gap: 25px;
}

.resume-card {
  height: 100%;
  transition: transform 0.3s;
  border-radius: 10px;
  overflow: hidden;
}

.resume-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 6px 20px rgba(0, 0, 0, 0.15);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
}

.resume-title {
  font-weight: bold;
  font-size: 18px;
  color: #409EFF;
}

.card-actions {
  display: flex;
  gap: 10px;
}

.card-button {
  transition: all 0.3s ease;
  font-weight: 500;
  padding: 6px 16px;
  border-radius: 6px;
}

.edit-btn:hover {
  background-color: #66b1ff;
  color: white;
}

.delete-btn:hover {
  background-color: #f56c6c;
  color: white;
}

.card-content {
  font-size: 14px;
  line-height: 1.6;
  padding: 10px 5px;
}

.card-content p {
  margin: 10px 0;
}

.skills-section {
  margin-top: 15px;
}

.skills-text {
  white-space: pre-line;
  color: #606266;
  margin-top: 4px;
  font-size: 13px;
  line-height: 1.5;
  max-height: 100px;
  overflow: hidden;
}

.update-time {
  font-size: 12px;
  color: #909399;
  margin-top: 10px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 15px;
  margin-top: 10px;
}

.cancel-btn, .save-btn {
  padding: 10px 24px;
  font-size: 16px;
  border-radius: 8px;
  font-weight: 500;
  transition: all 0.3s ease;
}

.cancel-btn:hover {
  background-color: #f2f6fc;
}

.save-btn:hover {
  opacity: 0.9;
}

.resume-dialog :deep(.el-form-item__label) {
  font-weight: 500;
}

.application-panel {
  width: 500px;
  position: sticky;
  top: 20px;
  height: fit-content;
}

.application-card {
  height: 100%;
}

.panel-title {
  font-size: 18px;
  font-weight: bold;
  color: #409EFF;
}

.job-description, .job-requirements {
  margin-top: 15px;
}

.description-text {
  white-space: pre-line;
  color: #606266;
  margin-top: 4px;
  font-size: 13px;
  line-height: 1.5;
}
</style>